package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.redis.JobRedisKey;
import cn.wolfcode.web.feign.SeckillProductFeignApi;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by wolfcode-lanxw
 */
@Component
@Setter@Getter
public class SeckillProductCacheJob implements SimpleJob {
    @Value("${jobCron.initSeckillProduct}")
    private String cron;
    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void execute(ShardingContext shardingContext) {
        //获取到分片的参数
        String time = shardingContext.getShardingParameter();
        //远程调用秒杀服务，根据场次查询当天的商品的集合数据
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.queryByTimeForJob(Integer.parseInt(time));
        if(result==null || result.hasError()){
            //通过短信或者邮件方式通知运维人员.
            return;
        }
        //删除前一天的数据
        String seckillProductKey = JobRedisKey.SECKILL_PRODUCT_HASH.getRealKey(time);
        String stockCountKey = JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time);
        redisTemplate.delete(seckillProductKey);
        redisTemplate.delete(stockCountKey);
        //将查询到的数据放入到Redis中
        List<SeckillProductVo> voList = result.getData();
        for(SeckillProductVo vo:voList){
            redisTemplate.opsForHash().put(seckillProductKey,String.valueOf(vo.getId()), JSON.toJSONString(vo));
            redisTemplate.opsForHash().put(stockCountKey,String.valueOf(vo.getId()), String.valueOf(vo.getStockCount()));
        }
        System.out.println("定时上线完成");
    }
}
